/**
 * Created by Administrator on 2018/12/17 0017.
 */
layui.define(['index'], function(exports){
    var $ = layui.$,
        form = layui.form,
        upload = layui.upload;
    $("#spec").click(function (){
        var cons = $(".gui-content").length;
        if (cons > 1){
            layer.msg('最多只能添加两组规格');
        }else{
            $(this).before('<div class="gui-content">' +
                '<div class="layui-input-inline gui-inline">' +
                '<div class="gui-flex"><div class="gui-selects">' +
                '<select name="spec" lay-filter="ziding">' +
                '<option value="颜色">颜色</option>' +
                '<option value="尺寸">尺寸</option>' +
                '<option value="尺码">尺码</option>' +
                '<option value="规格">规格</option>' +
                '<option value="容量">容量</option>' +
                '<option value="含量">含量</option>' +
                '<option value="款式">款式</option>' +
                '<option value="种类">种类</option>' +
                '<option value="型号">型号</option>' +
                '<option value="品牌">品牌</option>' +
                '<option value="包装">包装</option>' +
                '<option value="重量">重量</option>' +
                '<option value="口味">口味</option>' +
                '<option value="材质">材质</option>' +
                '<option value="自定义">自定义</option>' +
                '</select></div><div class="gui-picture">' +
                '<input type="checkbox" class="gupi" lay-filter="gupi" lay-skin="primary" title="添加规格图片">' +
                '</div><div class="guanbi">X</div></div></div>' +
                '<div class="gui-flex"><div class="tianjia">+添加</div></div></div>');
            form.render();
        }
    });

    //鼠标移入显示关闭按钮
    $(document).on('mouseover', '.layui-input-inline', function() {
        $(this).find(".guanbi").show();
    });

    //鼠标移出隐藏关闭按钮
    $(document).on('mouseout', '.layui-input-inline', function() {
        $(this).find(".guanbi").hide();
    });

    //点击关闭按钮删除当前规格
    $(document).on('click', '.guanbi', function() {
        var index = $(".gui-content .guanbi").index(this);
        var counts = $(".gui-content").length;
        var shanchu = $(this).parents('.gui-content').find('.spec-relative').length;
        if (shanchu > 0){
            if (index != -1 && index == 0){ //删除第一个
                var num = $(".gui-content:first").find('.spec-relative').length;
                var geshu = $(".gui-content").length;
                if (geshu == '1'){ //直接删除
                    $("#tables thead").html('');
                    $(".shezhi").prevAll().remove();
                    $("#stock").prop('disabled', false);
                    $("#price").prop('disabled', false);
                    $("#weight").prop('disabled', false);
                    $(".kucun").hide();
                }else{
                    var del = (num - 1); //要删除的个数
                    var content_num = 4;
                    $(".gui-content").each(function (index2){
                        var dang = $(this).find('.spec-relative').length;
                        if (index2 > 0){
                            if (dang > 0){
                                del = del * dang;
                            }
                        }
                        if (dang > 0){
                            content_num += 1;
                        }
                    });
                    $("#tables thead tr th:first").remove();
                    for (var count = 0; count < del; count++) {
                        $("#tables tbody tr").eq(-2).remove();
                    }
                    $("#tables tbody tr").each(function (){
                        $(this).find('td').eq(-content_num).remove();
                    });
                }
            }else if(index + 1 == counts){ //删除最后面的
                $("#tables thead tr th").eq(index).remove();
                $("#tables tbody tr:not('.shezhi')").each(function (indexsss){
                    if ($(this).find('td').length == 5){
                        $(this).remove();
                    }else{
                        $(this).find('td').eq(-5).remove();
                    }
                });
            }
        }
        $(this).parents('.gui-content').remove();
        rowspan();
    });

    //点击添加子规格按钮
    $(document).on('click', '.tianjia', function() {
        if ($(this).find(".gui-whole").length == 0){
            var html = '' +
                '<div class="spec-relative"><span class="arrow"></span><div class="gui-whole">' +
                '<input class="layui-input gui-input">' +
                '<button class="layui-btn layui-btn-sm layui-btn-normal queding">确定</button>' +
                '<button class="layui-btn layui-btn-sm layui-btn-primary cancel">取消</button>' +
                '</div></div>';
            $(this).append(html);
            $(this).find('input').focus();
        }else{
            $(this).find('input').focus();
        }
    });

    //规格自定义
    form.on('select(ziding)', function(data){
        var value = data.value;
        var that = data.othis.parent('.gui-selects');
        var is = data.othis.parent('.gui-selects').nextAll('.zidingyi').length;
        if (value === '自定义'){
            //判断没有才能添加
            if(is == 0){
                var html = '<div class="zidingyi"><input class="layui-input" name="zidingyi" lay-verify="required"></div>';
                that.after(html);
            }
        }else{
            that.next(".zidingyi").remove();
            //判断下级是否存在
            var length = $(that).parents('.gui-content').find('.gui-flex .spec-relative .zilei').length;
            if (length > 0){
                var index = $(".gui-content .gui-selects").index(that);
                $("#tables thead tr th").eq(index).html(value);
            }
        }
    });

    //监听input框输入
    $(document).on('input propertychange', '.zidingyi', function() {
        var value = $(this).find('input').val();
        var length = $(this).parents('.gui-content').find('.gui-flex .spec-relative .zilei').length;
        if (length > 0){
            var index = $(this).parents(".gui-content").index();
            $("#tables thead tr th").eq(index).html(value);
        }
    });

    //监听input框点击
    $(document).on('click', '.zidingyi', function() {
        $(this).find('input').css('border-color', '#C9C9C9');
    });

    //添加子规格按钮确认
    $(document).on('click', '.queding', function() {
        //去除没有子类的规格
        var anIndex = $(".gui-content").index($(this).parents('.gui-content'));
        $(".gui-content").each(function(list){
            //只删除当前元素以外的
            if (anIndex != list){
                if ($(this).find('.gui-flex .spec-relative .zilei').length == 0){
                    $(this).remove();
                }
            }
        });
        add(this);
        return false;
    });

    //添加子规格回车
    $(document).on('keypress', '.gui-input', function(e) {
        //去除没有子类的规格
        if (e.keyCode == 13){
            var anIndex = $(".gui-content").index($(this).parents('.gui-content'));
            $(".gui-content").each(function(list){
                //只删除当前元素以外的
                if (anIndex != list){
                    if ($(this).find('.gui-flex .spec-relative .zilei').length == 0){
                        $(this).remove();
                    }
                }
            });
            add($(this).next('.queding'));
        }
    });

    //添加子规格
    function add(obj){
        var index = $(obj).parents('.gui-content').index();
        var fu = $(obj).parents('.gui-flex').prev('.gui-inline').find('select[name=spec] option:selected').val();
        var value = $.trim($(obj).prev().val());
        var re = false;
        var html = '';
        var checked = $(obj).parents('.gui-flex').prev('.gui-inline').find('.gupi').is(':checked');
        $($(this).parents('.tianjia').prevAll()).each(function () {
            var yiyou = $(obj).find(".zilei").text();
            if (value == yiyou){
                re = true;
            }
        });
        if (fu == '自定义'){
            fu = $(".zidingyi").find('input').val();
        }
        if (!fu){
            layer.tips('规格名称不能为空', $(obj).parents('.gui-content').find('.zidingyi input'), {
                tips: 1
            });
            $(obj).parents('.gui-content').find('.zidingyi input').css('border-color', 'red');
            return false;
        }
        if (re || !value){
            layer.tips('值不能为空或者重复', $(obj).parent(), {
                tips: 1
            });
            $(obj).prev().css('border-color', 'red');
            return false;
        }
        if (checked){
            html = '<div class="spec-relative"><div class="zilei-close">X</div><div class="zilei">'+value+'</div><div class="add-picture">+</div></div>';
        }else{
            html = '<div class="spec-relative"><div class="zilei-close">X</div><div class="zilei">'+value+'</div></div>';
        }
        $(obj).parents('.tianjia').before(html);
        //添加disabled
        $("#stock").prop('disabled', true);
        $("#price").prop('disabled', true);
        $("#weight").prop('disabled', true);
        var index2 = $(obj).parents('.tianjia').prevAll().length - 1;
        stock(index, fu, index2, value);
        $(obj).parents('.spec-relative').remove();
    }

    //添加子规格按钮取消
    $(document).on('click', '.cancel', function() {
        $(this).parents('.spec-relative').remove();
        return false;
    });

    //移入子元素显示关闭按钮
    $(document).on('mouseover', '.spec-relative', function (){
        $(this).find(".zilei-close").show();
    });

    //移出子元素显示关闭按钮
    $(document).on('mouseout', '.spec-relative', function (){
        $(this).find(".zilei-close").hide();
    });

    //移入关闭按钮
    $(document).on('mouseover', '.zilei-close', function (){
        $(this).css('background', '#ff661c');
    });

    //移出关闭按钮
    $(document).on('mouseout', '.zilei-close', function (){
        $(this).css('background', '#0000004d');
    });

    //点击关闭按钮
    $(document).on('click', '.zilei-close', function (){
        var index = $(this).parents('.gui-content').index(); //所在规格位置
        var index2 = $(this).parents('.spec-relative').index(); //所在子规格位置
        var shu = $(this).parents('.gui-flex').find('.zilei').length; //当前位置剩余的子规格数量
        var value = $(this).next('.zilei').html(); //当前删除的值
        var whole = $('.gui-content').find('.zilei').length;
        if (index == 0){ //删除第一个规格下的参数
            if (shu-1 == 0){
                $('#tables thead tr th:first').remove();
                $(this).parents('.gui-content').remove();
                //待完善
                $("#tables tbody tr:not('.shezhi')").each(function (){
                    $(this).find('td').eq(-6).remove();
                });
                rowspan();
            }else{
                $("#tables tbody tr").each(function (indexs){
                    if ($(this).prop("className") != 'shezhi'){
                        var group = $(this).attr('data-group');
                        var groups = group.split(",");
                        if (groups[index] == value){
                            $(this).remove();
                        }
                    }
                });
            }
            if (whole - 1 == 0){ //全部删除
                $("#tables thead tr").remove();
                $("#tables tbody tr:not('.shezhi')").remove();
                $("#stock").prop('disabled', false);
                $("#price").prop('disabled', false);
                $("#weight").prop('disabled', false);
                $('.kucun').hide();
            }
        }else{
            if (index2 == 0){ //删除第一个子规格
                if (shu-1 == 0){ //全部删除
                    $("#tables thead tr th").eq(index).remove();
                    $("#tables tbody tr").each(function (){
                        var trLength = $(this).find('td').length;
                        var xunhuan = trLength-4; //当前参数后面有几个参数
                        for (var i=0;i<xunhuan;i++){
                            var huo = xunhuan-i; //循环条件(次数)
                            //获取规格倒数huo两个数加入数组 然后相乘等于rowspan的数
                            var zhi = 1;
                            for (var z=0;z<huo;z++){
                                var chang = 1;
                                if (z == 0){
                                    chang = $(".gui-content").eq(-(z+1)).find(".gui-flex .spec-relative .zilei").length - 1;
                                }else{
                                    chang = $(".gui-content").eq(-(z+1)).find(".gui-flex .spec-relative .zilei").length;
                                }
                                zhi = zhi*chang;
                            }
                            if (!zhi){
                                zhi = 1
                            }
                            $(this).find('td').eq(i).attr('rowspan', zhi)
                        }
                        $(this).find('td').eq(-5).remove();
                    });
                }else{ //删除第一个
                    $("#tables tbody tr").each(function (indexs){
                        if ($(this).prop("className") != 'shezhi'){
                            var group = $(this).attr('data-group');
                            var groups = group.split(",");
                            if (groups[index] == value){
                                var tdhtml = $(this).find('td:first').prop("outerHTML");
                                $(this).next().prepend(tdhtml);
                                $(this).remove();
                            }
                        }
                    });
                    houDelete();
                }
            }else{
                houDelete();
                $("#tables tbody tr").each(function (indexs){
                    if ($(this).prop("className") != 'shezhi'){
                        var group = $(this).attr('data-group');
                        var groups = group.split(",");
                        if (groups[index] == value){
                            $(this).remove();
                        }
                    }
                });
            }
        }
        $(this).parent('.spec-relative').remove();
    });

    //后面的删除
    function houDelete(){
        $("#tables tbody tr").each(function(){
            //所有tr的长度
            var trLength = $(this).find('td').length;
            if (trLength > 5){
                var xunhuan = trLength-5; //当前参数后面有几个参数
                for (var i=0;i<xunhuan;i++){
                    var huo = xunhuan-i; //循环条件(次数)
                    //获取规格倒数huo两个数加入数组 然后相乘等于rowspan的数
                    var zhi = 1;
                    for (var z=0;z<huo;z++){
                        var chang = 1;
                        if (z == 0){
                            chang = $(".gui-content").eq(-(z+1)).find(".gui-flex .spec-relative .zilei").length - 1;
                        }else{
                            chang = $(".gui-content").eq(-(z+1)).find(".gui-flex .spec-relative .zilei").length;
                        }
                        zhi = zhi*chang;
                    }
                    $(this).find('td').eq(i).attr('rowspan', zhi)
                }
            }
        });
    }

    //添加规格图片
    form.on('checkbox(gupi)', function(data){
        //所有值得dom
        var zhi = data.othis.parents(".gui-inline").next(".gui-flex").find(".spec-relative");
        var html = '<div class="add-picture">+</div>';
        //判断当前是否选中
        if (data.elem.checked){
            $(zhi).each(function (){
                $(this).append(html);
            });
        }else{
            $(zhi).each(function (){
                $(this).find('.add-picture').remove();
            });
        }
    });

    //上传规格图片
    $(document).on('click', '.add-picture', function (){
        $("#upload").click();
        $("#upload").data('this', $(this));
    });

    //普通图片上传
    upload.render({
        elem: '#upload'
        ,url: '/admin/Product/specUpload'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $($("#upload").data('this')).html('');
                $($("#upload").data('this')).append('<img src="'+result+'"  style="width: 100%;height: 100%;">');
            });
        }
        ,done: function(res){
            //如果上传失败
            if(res.error > 0){
                return layer.msg('上传失败');
            }
            //上传成功
            layer.msg('上传成功');
            $($("#upload").data('this')).append('<input type="hidden" name="upload" value="'+res.url+'" >');
        }
    });

    //判断是否有值并且显示库存
    function stock(index, fu, index2, value){
        var ge = $('.zilei').length;
        var th = '';
        var td = '';
        if (ge > 0){
            $('.kucun').show();
            //有参数则不能自己设置
            $("#stock").prop('disabled', true);
            $("#price").prop('disabled', true);
            $("#weight").prop('disabled', true);
        }else{
            $('.kucun').hide();
        }
        //获取一个tr的rowspan大小用于循环获取多少个tr
        var diYi = $("#tables tbody tr td").attr('rowspan');
        //获取当前td的名称用于替换
        var yTd = $("#tables tbody tr:first td:first").html();
        //判断th是否存在
        if (index == 0){// 添加规格第一次
            if (index2 == 0){ //添加属性第一次
                th = '<tr><th>'+fu+'</th><th>价格</th><th>库存</th><th>成本价</th><th>重量(kg)</th></tr>';
                td = '<tr><td>'+value+'</td>' +
                    '<td><input type="number" name="price" class="layui-input table-input" lay-verify="required|number"></td>' +
                    '<td><input type="number" name="stock" class="layui-input table-input" lay-verify="required|number"></td>' +
                    '<td><input type="number" name="cost" class="layui-input table-input" lay-verify="required|number"></td>' +
                    '<td><input type="number" name="weight" class="layui-input table-input" lay-verify="required|number"></td></<tr>';
                $("#tables thead").append(th);
                $("#tables tbody tr:last").before(td);
            }else{
                var yuan = '';
                var news = '';
                if (!diYi){
                    diYi = 1;
                    yuan = '<td>'+yTd+'</td>';
                    news = '<td>'+value+'</td>';
                }else{
                    yuan = '<td rowspan="'+diYi+'">'+yTd+'</td>';
                    news = '<td rowspan="'+diYi+'">'+value+'</td>';
                }
                for (var i=0;i<diYi;i++){
                    td += $("#tables tbody tr").eq(i).prop("outerHTML");
                }
                //替换
                td = replace(td, yuan, news);
                $("#tables tbody tr:last").before(td);
            }
        }else{ //后面添加规格
            if (index2 == 0){ //添加属性第一次
                th = '<th>'+fu+'</th>';
                td = '<td>'+value+'</td>';
                $("#tables thead tr th").eq(-4).before(th);
                $("#tables tbody tr.shezhi").prevAll().each(function(){
                    $(this).find('td').eq(-4).before(td);
                });
            }else{
                //如果后面有参数获取后面的参数数量查找td用于拼接
                var hou = 1;
                $(".gui-content").eq(index).nextAll(".gui-content").each(function(){
                    var shu = $(this).find('.zilei').length;
                    hou = hou*shu;
                });
                td = '<tr><td>'+value+'</td>';
                //获取已有的td长度
                $("#tables tbody tr:first td").eq(index).nextAll().each(function(){
                    td += $(this).prop("outerHTML");
                });
                td += '</tr>';
                for (var s=0;s<hou;s++){
                    if (s!=0){
                        td += $("#tables tbody tr").eq(s).prop("outerHTML");
                    }
                }
                //添加td
                $("#tables tbody tr").each(function(indexs){
                    if (hou){
                        if (indexs%((index2)*hou) == 0 && indexs != 0){
                            $(this).before(td);
                        }
                    }else{
                        if (indexs%index2 == 0 && indexs != 0){
                            $(this).before(td);
                        }
                    }
                });
            }
        }
        //把当前rowspan加大
        rowspan();
        //当前添加的规格个数
        $(".shezhi td").attr('colspan', index+5);
    }

    var group = [];
    //rowspan
    function rowspan(){
        $("#tables tbody tr").each(function(xu){
            //所有tr的长度
            var trLength = $(this).find('td').length;
            if (trLength > 5){
                var xunhuan = trLength-5; //当前参数后面有几个参数
                for (var i=0;i<xunhuan;i++){
                    var huo = xunhuan-i; //循环条件(次数)
                    //获取规格倒数huo两个数加入数组 然后相乘等于rowspan的数
                    var zhi = 1;
                    for (var z=0;z<huo;z++){
                        var chang = $(".gui-content").eq(-(z+1)).find(".gui-flex .spec-relative .zilei").length;
                        zhi = zhi*chang
                    }
                    $(this).find('td').eq(i).attr('rowspan', zhi)
                }
            }else if (trLength == 5){
                $(this).find('td').eq(0).attr('rowspan', 1)
            }
            //当前规格长度
            var gc = $(".gui-content").length;
            if (gc == trLength - 4){
                group = [];
                for (var g=0;g<gc;g++){
                    group.push($(this).find('td').eq(g).html());
                }
                group.join(',');
                $(this).attr('data-group', group);
            }
            if ($(this).prop("className") != 'shezhi'){
                if (gc != trLength - 4){
                    var duo = trLength-4;
                    for (var d=0;d<duo;d++){
                        group.splice(-(d+1), 1, $(this).find('td').eq(-(d+5)).html());
                    }
                    group.join(',');
                    $(this).attr('data-group', group);
                }
            }
        });
    }

    //替换字符
    function replace(str, yuan, news) {
        re = new RegExp(yuan, "g");
        return str.replace(re, news);
    }

    //批量设置
    $(".repertory_tableoption a").on('click', function(){
        var that = $(this).parent('.repertory_tableoption').next('.repertory_tableform');
        var lei = $(this).data('input');
        that.show();
        that.find('input').focus();
        that.find('input').data('target', lei);
        that.find('input').val('');
        if (lei == 'sku_price'){
            that.find('input').attr('placeholder', '请输入价格');
        } else if (lei == 'sku_stock'){
            that.find('input').attr('placeholder', '请输入库存');
        } else if (lei == 'sku_cost'){
            that.find('input').attr('placeholder', '请输入成本价');
        } else if (lei == 'sku_weight'){
            that.find('input').attr('placeholder', '请输入重量');
        }
    });

    //取消
    $(".setcancel").on('click', function(){
        $(this).parents('.repertory_tableform').hide();
        $(this).parents('.repertory_tableform').find('input').css('border-color', '#e6e6e6');

    });

    //保存
    $(".setok").on('click', function(){
        var that = $(this).parent().prev().find('input');
        var value = parseFloat(that.val()); //字符串转换为浮点型
        var lei = that.data('target');
        if (!value){
            layer.tips('值不能为空', that, {
                tips: 1
            });
            that.css('border-color', 'red');
            return false;
        }
        if (isNaN(value)){
            layer.tips('请输入数字', that, {
                tips: 1
            });
            that.css('border-color', 'red');
            return false;
        }
        if (lei == 'sku_price'){
            $("#tables input[name=price]").val(returnFloat(value));
        } else if (lei == 'sku_stock'){
            if (!isInteger(value)){
                layer.tips('请输入整数', that, {
                    tips: 1
                });
                that.css('border-color', 'red');
                return false;
            }
            $("#tables input[name=stock]").val(value);
        } else if (lei == 'sku_cost'){
            $("#tables input[name=cost]").val(returnFloat(value));
        } else if (lei == 'sku_weight'){
            $("#tables input[name=weight]").val(returnFloat(value));
        }
        $(this).parents('.repertory_tableform').hide();
    });

    //判断是否为整数
    function isInteger(obj) {
        return Math.floor(obj) === obj
    }

    //补零
    function returnFloat(value){
        value = Math.round(parseFloat(value)*100)/100;
        var xsd = value.toString().split(".");
        if(xsd.length == 1){
            value = value.toString()+".00";
            return value;
        }
        if(xsd.length>1){
            if(xsd[1].length<2){
                value = value.toString()+"0";
            }
            return value;
        }
    }

    //监听运费
    form.on('select(yunfei)', function(data){
        var value = data.value;
        var that = data.othis.parent();
        var html = '<div class="layui-input-inline" style="width: 100px;">' +
            '<input type="number" name="freight" autocomplete="off" lay-verify="required|number" value="{$find.freight}" class="layui-input" style="padding-right:20px;">' +
            '<span style="position:absolute;right:5px;top:8px;color:#b9b9b9;">元</span>' +
            '</div>';
        if (value == 1){
            that.after(html);
        }else{
            that.next().remove();
        }
    });

    exports('spec', {});
});

